package com.tanchengjin.admin.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.tanchengjin.admin.enumerations.ConfigKey;
import com.tanchengjin.admin.model.dao.AdminConfigMapper;
import com.tanchengjin.admin.model.pojo.AdminConfig;
import com.tanchengjin.admin.model.vo.ConfigWebsiteVO;
import com.tanchengjin.admin.service.AdminConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * create by  admin_config ServiceImpl
 *
 * @author TanChengjin
 * @version v1.0.0
 * @since v1.0.0
 */
@Service("adminConfigService")
public class AdminConfigServiceImpl implements AdminConfigService {

    @Autowired
    private AdminConfigMapper adminConfigMapper;

    public AdminConfig findOneById(int id) {
        AdminConfig adminConfig = adminConfigMapper.selectByPrimaryKey(id);
        return adminConfig;
    }

    public int deleteById(int id) {
        int i = adminConfigMapper.deleteByPrimaryKey(id);
        return i;

    }

    public int create(AdminConfig adminConfig, ConfigKey configKey) {
        adminConfig.setKey(configKey.getKey());
        int i = adminConfigMapper.insertSelective(adminConfig);
        return i;
    }

    public int updateById(AdminConfig adminConfig, int id) {
        adminConfig.setId(id);
        int i = adminConfigMapper.updateByPrimaryKeySelective(adminConfig);
        return i;
    }

    public List<AdminConfig> getAll() {
        List<AdminConfig> adminConfigList = adminConfigMapper.getAll();
        return adminConfigList;
    }

    public List<AdminConfig> getAllByCondition(AdminConfig adminConfig) {
        List<AdminConfig> adminConfigList = adminConfigMapper.getAllByCondition(adminConfig);
        return adminConfigList;
    }

    @Override
    public int batchDelete(int[] ids) {
        int i = 0;
        for (int id : ids) {
            i += adminConfigMapper.deleteByPrimaryKey(id);
        }
        return i;
    }

    @Override
    public int count() {
        return adminConfigMapper.count();
    }

    @Override
    public int updateByKey(ConfigWebsiteVO websiteVO, ConfigKey configKey) {
        int i = 0;
        AdminConfig adminConfig1 = adminConfigMapper.selectByKey(configKey.getKey());
        if (adminConfig1 == null) {
            AdminConfig adminConfig = new AdminConfig();
            adminConfig.setKey(configKey.getKey());
            String s = "";
            try {
                s = (new JsonMapper()).writeValueAsString(websiteVO);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            adminConfig.setContent(s);
            i += create(adminConfig, configKey);
        } else {
            i += updateById(adminConfig1, adminConfig1.getId());
        }
        return i;
    }
}